//
//  MTWeiboManager.m
//  huipai_3
//
//  Created by tan xi on 11-9-8.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#define kSinaOAuthConsumerKey				@"4252632787" //huipai appkey
#define kSinaOAuthConsumerSecret			@"9dc6c472b73b09551db52f491711158f"

#define kTencentOAuthConsumerKey			@"801002893" //zrz appkey
#define kTencentOAuthConsumerSecret			@"1f2685ca89063ee0feee6b299e7559df"

#define kKaixinOAuthConsumerKey             @"348468806373d5942343e6f3773bd713" //zrz appkey
#define kKaixinOAuthConsumerSecret          @"f86b46780531f632a9224736dbbb6651"
#define kKaixinOAuthScope                   @"basic user_birthday user_intro user_career create_records create_album upload_photo send_message " 

#define kRenrenOAuthConsumerKey             @"d39507214c734be590620f5a9337cc58"
#define kRenrenOAuthConsumerID              @"64438fb7b0894b5f8d5ee01656ecc41f"
#define kRenrenOAuthScope                   @"photo_upload publish_feed status_update operate_like"

#define kDoubanOAuthConsumerKey             @"043de85a621426300cb9b90f263c7290"
#define kDoubanOAuthConsumerSecret          @"99ab509b40129a49"

#define kQQOAuthConsumerKey                 @"223213"
#define kQQOAuthScope                       @"get_user_info,add_share"

#define defaulteUser     @"defaulteUser"

#define makeStoreString(type, userName) [NSString stringWithFormat:@"%@_%@_accessToken", weiboString(type), userName]

#import "MTWeiboManager.h"
#import "QWeiboClient.h"
#import "WeiboClient.h"
#import "kxClient.h"
#import "NSURL+QAdditions.h"
#import "Draft.h"
#import "SBJSON.h"
#import "MTParseXML.h"

static NSString *QtokenKey;
static NSString *QtokenSecret;

NSString *weiboString(MTWMWeiboType type){
    switch(type){
        case MTWMSinaWeibo:
            return @"sina";
        case MTWMTencentWeibo:
            return @"tencent";
        case MTWMKaixin:
            return @"kaixin";
        case MTWMRenren:
            return @"renren";
        case MTWMDouban:
            return @"douban";
        case MTWMQQ:
            return @"QQtencent";
        default:
            return nil;
    }
}

BOOL isAuthedForKaiXin(NSString *weiboName, NSString *email)
{
    //get access token.noted by zrz.
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *accessToken = [defaults objectForKey:[NSString stringWithFormat:@"%@_%@_accessToken", weiboName, email]];
    //check that is this id right.noted by zrz.
    if ([accessToken length] > 0) {
        return YES;
    } else {
        return NO;
    }
}

@implementation MTWeiboManager

@synthesize delegate, userName;
@synthesize tempSina, tempKaixin;

- (id)init
{
    self = [super init];
    if (self) {
        //新浪
        sinaEngine = [[OAuthEngine alloc] initOAuthWithDelegate:self];
        sinaEngine.consumerKey = kSinaOAuthConsumerKey;
        sinaEngine.consumerSecret = kSinaOAuthConsumerSecret;
        [sinaEngine isAuthorized];
        
        //开心
        kxEngine = [[KxOAuthEngine alloc] initOAuthWithDelegate:self
                                                       andScope:kKaixinOAuthScope];
        kxEngine.consumerKey = kKaixinOAuthConsumerKey;
        kxEngine.consumerSecret = kKaixinOAuthConsumerSecret;
        [kxEngine isAuthorized];
        
        //腾讯微博
        if ([QWeiboClient isExit:userName]) {
            QClient = [[QWeiboClient alloc] initWithAppKey:kTencentOAuthConsumerKey
                                                 appSecret:kTencentOAuthConsumerSecret
                                                  tokenKey:nil
                                               tokenSecret:nil];
            QClient.delegate = self;
            QClient.weiboIndentify = weiboString(MTWMTencentWeibo);
            [QClient getSourceAccessToken:userName];
            
        }
        
        //人人网
        _renren = [[Renren alloc] initWithAppKeyAndId:kRenrenOAuthConsumerKey 
                                             andAppId:kRenrenOAuthConsumerID];
        _renren.sessionDelegate = self;
        
        //豆瓣
        _douban = [[MinroadOauth alloc] init];
        _douban.appKey = kDoubanOAuthConsumerKey;
        _douban.appSecret = kDoubanOAuthConsumerSecret;
        _douban.delegate = self;
        
        //qq登陆
        _QQOAuth = [[TencentOAuth alloc] initWithAppId:kQQOAuthConsumerKey
                                           andDelegate:self];
        _QQOAuth.redirectURI = @"www.qq.com";
        self.userName = defaulteUser;
    }
    return self;
}

- (id)initWithUserName:(NSString*)_userName
{
    self = [self init];
    if (self) {
        userName = _userName;
        [userName retain];
        _renren.userName = userName;
    }
    return self;
}

- (void)dealloc
{
    [sinaEngine release];
    [kxEngine   release];
    [QClient    release];
    [delegate   release];
    [_douban    release];
    [_renren    release];
    [super  dealloc];
}

- (BOOL)isLoginWithType:(MTWMWeiboType)type
{
    switch (type) {
        case MTWMSinaWeibo:
        case MTWMKaixin:
        case MTWMDouban:
        case MTWMQQ:
            return isAuthedForKaiXin(weiboString(type) , userName);
        case MTWMTencentWeibo:
            return [QWeiboClient isExit:userName];
        case MTWMRenren:
            return [_renren isSessionValid];
        default:
            return NO;
    }
}

- (void)deleteWeiboWithType:(MTWMWeiboType)type
{
    switch (type) {
        case MTWMSinaWeibo:
        case MTWMKaixin:
        case MTWMDouban:
        case MTWMQQ:
        {
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults removeObjectForKey:[NSString stringWithFormat:@"%@_%@_accessToken",
                                          weiboString(type), userName]];
            [defaults synchronize];
            NSLog(@"removeCachedOAuthDataForUsername!!!");
            break;
        }
        case MTWMTencentWeibo:
            [QWeiboClient delectThisToken:userName];
            break;
        case MTWMRenren:
            [_renren logout:self];
    }
}

- (void)saveWeiboWithType:(MTWMWeiboType)type
{
    NSString *saveData;
    switch (type) {
        case MTWMSinaWeibo:{
            saveData = self.tempSina;
            break;
        }
        case MTWMKaixin:
        {
            saveData = self.tempKaixin;
            break;
        }
        case MTWMTencentWeibo:
        {
            [QClient saveQAccessToken:userName];
            break;
        }
        case MTWMRenren:{
            _renren.userName = userName;
            [_renren createUserSessionInfo];
            break;
        }
        case MTWMDouban:{
            saveData = [NSString stringWithFormat:@"%@<->%@", _douban.token.key, _douban.token.secret];
            break;
        }
        case MTWMQQ:{
            saveData = [NSString stringWithFormat:@"%@<->%@", _QQOAuth.accessToken, _QQOAuth.openId];
            return;
        }
    }
    if (type != MTWMTencentWeibo) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:saveData
                     forKey:[NSString stringWithFormat:@"%@_%@_accessToken",
                             weiboString(type), userName]];
        [defaults synchronize];
    }
}

- (void)getSavedWeiboToken:(MTWMWeiboType)type{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *string = [defaults objectForKey:makeStoreString(type, userName)];
    switch (type) {
        case MTWMSinaWeibo:
        {
            OAToken *token = [[OAToken alloc] initWithHTTPResponseBody:string];
            sinaEngine.accessToken.key = token.key;
            sinaEngine.accessToken.secret = token.secret;
            sinaEngine.accessToken.pin = token.pin;
            break;
        }
        case MTWMKaixin:
        {
            OAToken *token = [[OAToken alloc] initWithHTTPResponseBody:string];
            kxEngine.accessToken.key = token.key;
            kxEngine.accessToken.secret = token.secret;
            kxEngine.accessToken.pin = token.pin;
            break;
        }
        case MTWMTencentWeibo:{
            [QClient getSourceAccessToken:userName];
            break;
        }
        case MTWMRenren:{
            _renren.userName = userName;
            [_renren isSessionValid];
            break;
        }
        case MTWMQQ:{
            NSArray *array = [string componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithContentsOfFile:@"<->"]];
            _QQOAuth.accessToken = [array objectAtIndex:0];
            _QQOAuth.openId = [array objectAtIndex:1];
        }
        case MTWMDouban:{
            NSArray *array = [string componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithContentsOfFile:@"<->"]];
            _douban.token.key = [array objectAtIndex:0];
            _douban.token.secret = [array objectAtIndex:1];
        }
    }
}

static UIViewController *tempCtrl;

- (void)showAuthentication:(UIViewController*)controller withType:(MTWMWeiboType)type
{
    switch (type) {
        case MTWMSinaWeibo:
        {
            OAuthController *oauthController = 
            [OAuthController controllerToEnterCredentialsWithEngine:sinaEngine
                                                           delegate:self];
            [controller presentModalViewController:oauthController 
                                          animated:YES];
            break;
        }
        case MTWMKaixin:
        {
            KxOAuthController *oauthController = 
            [KxOAuthController controllerToEnterCredentialsWithEngine:kxEngine
                                                             delegate:self];
            [controller presentModalViewController:oauthController
                                          animated:YES];
            break;
        }
        case MTWMTencentWeibo:
        {
            QWeiboSyncApi *api = [[[QWeiboSyncApi alloc] init] autorelease];
            NSString *retString = [api getRequestTokenWithConsumerKey:kTencentOAuthConsumerKey
                                                       consumerSecret:kTencentOAuthConsumerSecret];
            NSDictionary *params = [NSURL parseURLQueryString:retString];
            QtokenKey = [params objectForKey:@"oauth_token"];
            QtokenSecret = [params objectForKey:@"oauth_token_secret"];
            QVerifyWebViewController *verifyController = 
            [[QVerifyWebViewController alloc] initwithTokenKey:QtokenKey 
                                                   TokenSecret:QtokenSecret 
                                                        appKey:kTencentOAuthConsumerKey 
                                                     appSecret:kTencentOAuthConsumerSecret];
            verifyController.delegate = self;
            [controller presentModalViewController:verifyController 
                                          animated: YES];
            [verifyController release];
            break;
        }
        case MTWMRenren:
        {
            /*[_renren authorize:[NSArray arrayWithObject:kRenrenOAuthScope]
                      delegate:self];*/
            RenrenLoginViewController *ctrl = [_renren authorizeViewController:[NSArray arrayWithObject:kRenrenOAuthScope] delegate:self];
            [controller presentModalViewController:ctrl animated:YES];
        }
        case MTWMDouban:{
            _douban.viewController = controller;
            [_douban startOauth];
            break;
        }
        case MTWMQQ:{
            UIViewController *ctrl = [_QQOAuth getLoginViewController:[kQQOAuthScope componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@","]]];
            [controller presentModalViewController:ctrl animated:YES];
            tempCtrl = controller;
        }
        default:
            break;
    }
}

static NSString* _dataPath;

- (NSString*)dataPath
{
	if (_dataPath == NULL) {
		NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
		if ([documentPaths count]) {
			_dataPath = [[NSString alloc] initWithString:[documentPaths lastObject]];
		}
	}
	return _dataPath;
}

- (void)postType:(MTWMWeiboType)type Text:(NSString*)text imageData:(NSData*)data
{
    switch (type) {
        case MTWMSinaWeibo:
        {
            Draft *draft = [[Draft alloc] initWithType:DraftTypeNewTweet];
            draft.text = text;
            WeiboClient *_client = [[WeiboClient alloc] initWithTarget:self 
                                                                engine:sinaEngine
                                                                action:@selector(postStatusDidSucceed:obj:)];
            _client.context = draft;
            draft.draftStatus = DraftStatusSending;
            
            if (data) {
                [_client upload:data status:draft.text];
            } else {
                [_client post:draft.text];
            }
            break;
        }  
        case MTWMTencentWeibo:
        {
            NSString *savePath = [NSString stringWithFormat:@"%@/pixcoo.jpg", [self dataPath]];
            [data writeToFile:savePath atomically:YES];
            [QClient upload:text imagePath:savePath];
        }
        case MTWMKaixin:
        {
            kxClient *_kxClient = [[kxClient alloc] initWithTarget:self
                                                            engine:kxEngine
                                                            action:@selector(postStatusDidSucceed:obj:)];
            NSMutableDictionary *dic = [NSMutableDictionary
                                        dictionaryWithObjectsAndKeys:text, @"content",
                                        @"pixcoo", @"save_to_album",
                                        [UIImage imageWithData:data], @"pic", nil];
            [_kxClient sendRecord:dic];
            break;
        }
        case MTWMRenren:
        {
            if (data) {
                UIImage *img=[UIImage imageWithData:data];
                NSMutableDictionary *params=[NSMutableDictionary dictionaryWithObjectsAndKeys:
                                             @"photos.upload",@"method",
                                             img,@"upload",
                                             text, @"caption",
                                             nil];
                [_renren requestWithParams:params andDelegate:self];
            }else {
                NSMutableDictionary *params=[NSMutableDictionary dictionaryWithObjectsAndKeys:
                                             @"status.set",@"method",
                                             text, @"status",
                                             nil];
                [_renren requestWithParams:params andDelegate:self];
            }
            break;
        }
    }
}

//新浪微博engine
#pragma mark - sina engin delegate

- (void) storeCachedOAuthData: (NSString *) data forUsername: (NSString *) _username
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults setObject: data 
                 forKey:[NSString stringWithFormat:@"%@_%@_accessToken", 
                         weiboString(MTWMSinaWeibo), userName]];
	[defaults synchronize];
    self.tempSina = data;
    NSLog(@"storeCachedOAuthData!!!");
}

- (NSString *) cachedOAuthDataForUsername: (NSString *)_username
{
    NSLog(@"cachedOAuthDataForUsername!!!");

    if ([_username isEqualToString:defaulteUser]) {
        return nil;
    }
	return [[NSUserDefaults standardUserDefaults] 
            objectForKey:[NSString stringWithFormat:@"%@_%@_accessToken", 
                          weiboString(MTWMSinaWeibo), userName]];
}

//开心网engine
#pragma mark - kaixin engin delegate

- (void) kxStoreCachedOAuthData: (NSString *) data forUsername: (NSString *) username
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults setObject: data 
                 forKey:[NSString stringWithFormat:@"%@_%@_accessToken", 
                         weiboString(MTWMKaixin), userName]];
	[defaults synchronize];
    self.tempKaixin = data;
    NSLog(@"storeCachedOAuthData!!!");
}

- (NSString *) kxCachedOAuthDataForUsername: (NSString *) _username
{
    NSLog(@"cachedOAuthDataForUsername!!!");
    if ([_username isEqualToString:defaulteUser]) {
        return nil;
    }
	return [[NSUserDefaults standardUserDefaults] 
            objectForKey:[NSString stringWithFormat:@"%@_%@_accessToken", 
                          weiboString(MTWMKaixin), _username]];
}

//微博delegate
#pragma mark - weibo delegate

- (void) OAuthController: (UIViewController *) controller authenticatedWithUsername: (NSString *) username
{
    NSLog(@"Authenicated for %@!!!", username);
    if ([controller isMemberOfClass:[OAuthController class]]) {
        WeiboClient *weiboClient = [[WeiboClient alloc] initWithTarget:self 
                                                                engine:sinaEngine
                                                                action:@selector(userInfo:obj:)];
        [weiboClient getUser:[username intValue]];
    }
    else if ([controller isMemberOfClass:[KxOAuthController class]]) {
        kxClient *kxWeiboClient = [[kxClient alloc] initWithTarget:self
                                                            engine:kxEngine
                                                            action:@selector(kxUserInfo:obj:)];
        [kxWeiboClient getUserInfo];
    }
}
- (void) OAuthControllerFailed: (UIViewController *) controller {
	NSLog(@"Authentication Failed!!!!");
    if ([controller isMemberOfClass:[OAuthController class]]) {
        [self deleteWeiboWithType:MTWMSinaWeibo];
    }
    else if ([controller isMemberOfClass:[KxOAuthController class]]) {
        [self deleteWeiboWithType:MTWMKaixin];
    }
}

- (void) OAuthControllerCanceled: (UIViewController *) controller {
	NSLog(@"Authentication Canceled.!!!");
    if ([controller isMemberOfClass:[OAuthController class]]) {
        [self deleteWeiboWithType:MTWMSinaWeibo];
    }
    else if ([controller isMemberOfClass:[KxOAuthController class]]) {
        [self deleteWeiboWithType:MTWMKaixin];
    }
}

#pragma mark - renren delegate

-(void)rrDidLogin{
    //登录成功
    NSMutableDictionary *params=[NSMutableDictionary dictionaryWithObjectsAndKeys:
								 @"users.getInfo",@"method",
                                 @"uid,name,sex",@"fields",
								 nil];
	[_renren requestWithParams:params andDelegate:self];
}

-(void)rrDidLogout{
    //退出登录
}

-(void)rrDidNotLogin:(BOOL)cancelled {
	NSLog(@"did not login");
}

#pragma mark - renren request delegate

- (void)request:(Request *)request didFailWithError:(NSError *)error
{
    if ([delegate respondsToSelector:@selector(postInfoFaild:error:)]) 
        [delegate postInfoFaild:MTWMKaixin error:error];
}

- (void)request:(Request *)request didLoad:(id)result
{
    NSMutableDictionary* dict=request.params;
    NSString* methondname=[dict valueForKey:@"method"];
	if ([result isKindOfClass:[NSArray class]]) {
        if ([methondname isEqualToString:@"users.getInfo"]) {
            NSDictionary* dt=[result objectAtIndex:0];
            NSString* name=[dt objectForKey:@"name"];
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setObject:name 
                         forKey:[NSString stringWithFormat:@"%@_%@_screenName", 
                                 weiboString(MTWMRenren), 
                                 userName]];
            [defaults synchronize];
            if ([delegate respondsToSelector:@selector(userName:string:)])
                [delegate userName:MTWMRenren string:name];
        }else if ([methondname isEqualToString:@"photos.upload"] || 
                  [methondname isEqualToString:@"status.set"]) {
            if ([delegate respondsToSelector:@selector(postInfoSeccess:)])
                [delegate postInfoSeccess:MTWMRenren];
        }
	}
}

- (void)request:(Request *)request didLoadRawResponse:(NSData *)data
{
    
}

#pragma mark - tencent delegate

- (void)controller:(QVerifyWebViewController*)controller 
          tokenKey:(NSString*)tokenKey
       tokenSecret:(NSString*)tokenSecret 
            appKey:(NSString*)appKey
         appSecret:(NSString*)appSecret
{
    if (!QClient) QClient = [[QWeiboClient alloc] init];
    QClient.tokenKey = tokenKey;
    QClient.tokenSecret = tokenSecret;
    QClient.appKey = appKey;
    QClient.appSecret = appSecret;
    QClient.weiboIndentify = weiboString(MTWMTencentWeibo);
    QClient.delegate = self;
    [QClient getUserInfo];
}

#pragma mark - user info delegate

- (void)userInfo:(WeiboClient*)sender obj:(NSObject*)obj {
    NSLog(@"userInfo:obj:");
    if (sender.hasError) {
		NSLog(@"timelineDidReceive error!!!, errorMessage:%@, errordetail:%@"
			  , sender.errorMessage, sender.errorDetail);
        return;
    }
    NSDictionary *dic = (NSDictionary*)obj;
	User *responseUser = [[User alloc]initWithJsonDictionary:dic];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults setObject: responseUser.screenName 
                 forKey:[NSString stringWithFormat:@"%@_%@_screenName", 
                         weiboString(MTWMSinaWeibo), 
                         userName]];
	[defaults synchronize];
    [responseUser release];
    if ([delegate respondsToSelector:@selector(userName:string:)])
        [delegate userName:MTWMSinaWeibo string:responseUser.screenName];
}

- (void)postStatusDidSucceed:(WeiboClient*)sender obj:(NSObject*)obj;
{
    Draft *sentDraft = nil;
	if (sender.context && [sender.context isKindOfClass:[Draft class]]) {
		sentDraft = (Draft *)sender.context;
        [sentDraft release];
	}
	
    if (sender.hasError) {
        if ([delegate respondsToSelector:@selector(postInfoFaild:error:)]) 
            [delegate postInfoFaild:MTWMSinaWeibo error:[NSError errorWithDomain:sender.errorMessage
                                                                            code:101
                                                                        userInfo:nil]];
    } else {
        if ([delegate respondsToSelector:@selector(postInfoSeccess:)])
            [delegate postInfoSeccess:MTWMSinaWeibo];
    }
}

- (void)QUserInfo:(QWeiboClient*)sender dic:(NSDictionary*)dic
{
    NSLog(@"QuserInfo:obj:");
    NSString *_userName = [(NSDictionary*)[dic objectForKey:@"data"] objectForKey:@"name"];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults setObject:_userName
                 forKey:[NSString stringWithFormat:@"%@_%@_screenName", 
                         weiboString(MTWMTencentWeibo), userName]];
	[defaults synchronize];
    [sender saveQAccessToken:userName];
    if ([delegate respondsToSelector:@selector(userName:string:)])
        [delegate userName:MTWMTencentWeibo string:_userName];
}

- (void)QUploadOver:(NSError *)error
{
    if (error) {
        if ([delegate respondsToSelector:@selector(postInfoFaild:error:)]) 
            [delegate postInfoFaild:MTWMTencentWeibo error:error];
    } else {
        if ([delegate respondsToSelector:@selector(postInfoSeccess:)])
            [delegate postInfoSeccess:MTWMTencentWeibo];
    }
}

- (void)kxUserInfo:(kxClient*)sender obj:(NSObject*)obj {
    NSLog(@"userInfo:obj:");
    if (sender.hasError) {
		NSLog(@"timelineDidReceive error!!!, errorMessage:%@, errordetail:%@"
			  , sender.errorMessage, sender.errorDetail);
        return;
    }
    NSDictionary *dic = (NSDictionary*)obj;
	NSString *_userName = [dic objectForKey:@"name"];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults setObject:_userName 
                 forKey:[NSString stringWithFormat:@"%@_%@_screenName", 
                         weiboString(MTWMKaixin), 
                         userName]];
	[defaults synchronize];
    if ([delegate respondsToSelector:@selector(userName:string:)])
        [delegate userName:MTWMKaixin string:_userName];
}

- (void)kxPostStatusDidSucceed:(kxClient*)sender obj:(NSObject*)obj;
{
    Draft *sentDraft = nil;
	if (sender.context && [sender.context isKindOfClass:[Draft class]]) {
		sentDraft = (Draft *)sender.context;
        [sentDraft release];
	}
	NSLog(@"%@   ,   %@" , sender.errorMessage , sender.errorDetail);
    if (sender.hasError) {
        if ([delegate respondsToSelector:@selector(postInfoFaild:error:)]) 
            [delegate postInfoFaild:MTWMKaixin error:[NSError errorWithDomain:sender.errorMessage
                                                                            code:101
                                                                        userInfo:nil]];
    } else {
        if ([delegate respondsToSelector:@selector(postInfoSeccess:)])
            [delegate postInfoSeccess:MTWMKaixin];
    }
}

#pragma mark - renren private mothed

- (void)getUserInfo
{
    NSMutableDictionary *params=[NSMutableDictionary dictionaryWithObjectsAndKeys:
								 @"users.getInfo",@"method",
                                 @"uid,name",@"fields",
								 nil];
	[_renren requestWithParams:params andDelegate:self];
}

- (void)setUserName:(NSString *)_userName
{
    [userName release];
    userName = _userName;
    [userName retain];
    
    _renren.userName = userName;
}

#pragma mark - douban delegate
 
- (void)OauthDidFinish:(OAToken *)token
{
    [_douban getUserInfo];
}

- (void)infoGetSuccess:(NSData *)data
{
    MTParseXML *parser = [[MTParseXML alloc] initWithData:data];
    MTParseXMLPoint *root = [parser getRootPoint];
    MTParseXMLPoint *namenode = [root childWithName:@"title" index:0];
    NSString *nameString = [namenode getContent];
    if ([delegate respondsToSelector:@selector(userName:string:)])
        [delegate userName:MTWMDouban string:nameString];
}

#pragma mark - QQ delegate

- (void)tencentDidLogin
{
    [_QQOAuth getUserInfo];
}

- (void)getUserInfoResponse:(APIResponse*) response
{
    if (response.retCode == URLREQUEST_SUCCEED)
	{
        if ([tempCtrl respondsToSelector:@selector(dismissModalViewControllerAnimated:)]) {
            [tempCtrl dismissModalViewControllerAnimated:YES];
        }
        NSString *nickname = [response.jsonResponse objectForKey:@"nickname"];
        NSLog(@"%@", response.jsonResponse);
        if ([delegate respondsToSelector:@selector(userName:string:)])
            [delegate userName:MTWMDouban string:nickname];
    }else {
        
    }
    
}

@end
